package com.share.cloudStorage.users.controller;
import cn.hutool.core.io.FileUtil;
import com.share.cloudStorage.model.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import static com.share.cloudStorage.constant.Constants.ROOT_PATH;
@Slf4j
@RestController
@RequestMapping("api/v1/File")
@Validated
public class FileController {
    @PostMapping("/upload")
    public Result upload(MultipartFile file) throws IOException{
        String originalFilename = file.getOriginalFilename();//aaa.png
        String mainName = FileUtil.mainName(originalFilename);//aaa
        String extName = FileUtil.extName(originalFilename);//png
        if (!FileUtil.exist(ROOT_PATH)) {
            FileUtil.mkdir(ROOT_PATH);
        }
        if (FileUtil.exist(ROOT_PATH + File.separator + originalFilename)) {
            originalFilename = System.currentTimeMillis() + "_" + mainName + "." + extName;
        }
        File saveFile = new File(ROOT_PATH + File.separator + originalFilename);
        file.transferTo(saveFile);
        String url = originalFilename;
        return Result.ok(url);
    }
    @GetMapping("/download/{fileName}")
    public void download(@PathVariable String fileName, HttpServletResponse httpServletResponse) throws IOException {
        String filePath = ROOT_PATH + File.separator + fileName;
        log.info("filePath:{}", filePath);
        if (!FileUtil.exist(filePath)) {
            return;
        }
        byte[] bytes = FileUtil.readBytes(filePath);
        ServletOutputStream outputStream = httpServletResponse.getOutputStream();
        outputStream.write(bytes);
        outputStream.flush();
        outputStream.close();
    }
}
